﻿/**
* @description	Singleton that manages collection of StyleFormat instances to be used to color and style components.
*/
package com.foed.managers {

	import com.foed.graphic.StyleFormat;
	import com.foed.graphic.IStyleable;
	
	public class StyleManager {
	
		private static var sStyleManager:StyleManager;
	
		private var _styles:Object = {};
		private var _listeners:Object = {};
	
		/**
		* @description	Returns the Singleton instance of the StyleManager.
		*
		* @returns  The only StyleManager instance.
		*/
		static public function getInstance():StyleManager {
			if (sStyleManager == null) sStyleManager = new StyleManager();
			return sStyleManager;
		}
	
		/**
		* @description	Adds a StyleFormat instance to the collection of styles.
		*
		* @param  pName  The name to use to store the StyleFormat instance.
		* @param  pFormat  The StyleFormat instance to store.
		*/
		public function addStyle(pName:String, pFormat:StyleFormat):void {
			_styles[pName] = pFormat;
		}
	
		/**
		* @description	Removes a StyleFormat instance from the collection of styles.
		*
		* @param  pName  The name of the StyleFormat instance to remove.
		*/
		public function removeStyle(pName:String):void {
			delete _styles[pName];
		}
	
		/**
		* @description	Applies the appropriate style format to the specified object.
		*
		* @param  pObj  The object to which to apply a style format.
		*/
		public function style(pObj:IStyleable):void {
			var pFormat:StyleFormat = getStyle(pObj);
			pFormat.addListener(pObj);
			pObj.setStyleFormat(pFormat);
		}
			
		/**
		* @description	Finds the correct style format for an object based on instance or class hierarchy.
		*
		* @param  pObj  The object for which to find the appropriate style format.
		*
		* @returns  The style format to apply to the specified object.
		*/
		public function getStyle(pObj:IStyleable):StyleFormat {
			var pStyleFormatName:String = pObj.getStyleFormatName();
			if (pStyleFormatName != null) {
				for (var j:String in _styles) {
					if (_styles[j].name == pStyleFormatName) {
						return _styles[j];
					}
				}
			}
			var pClasses:Array = pObj.getClassHierarchy();
			for (var i:int = pClasses.length-1; i > -1; i--) {
				if (_styles[pClasses[i]] != undefined) return _styles[pClasses[i]];
			}
			return _styles["default"];
		}
	
	}
	
}